# -  *  - coding:utf-8  -  *  -
from selenium import webdriver

from public.common.readData import Data

elementsInfo = Data()
loginData = Data("loginparam")


class Page(object):

    base_url = "https://ancaiyun.com/"

    def __init__(self, dirver=None, url=base_url ):
        if not dirver:
            self.dirver = webdriver.Chrome()
        else:
            self.dirver = dirver
        self.base_url = url

    def _open(self, url):
        url = self.base_url + url
        try:
            self.dirver.get(url)
        except Exception as e:
            raise e

    def open(self, url=None):
        self._open(url)

    def get_element(self, *loc):
        self.dirver.implicitly_wait(10)
        try:
            el = self.dirver.find_element(*loc)
        except Exception as e:
            raise e
        return el

    def get_elements(self, *loc):
        self.dirver.implicitly_wait(10)
        try:
            els = self.dirver.find_element(*loc)
        except Exception as e:
            raise e
        return els

    def get_text(self, *loc):
        el = self.get_element(*loc)
        try:
            text = el.text
        except Exception as e:
            raise e
        return text

    def is_click(self, *loc):
        el = self.get_element(*loc)
        try:
            el.click()
        except Exception as e:
            raise e

    def accept_alter(self):
        try:
            self.dirver.switch_to.alert.accept()
        except Exception as e:
            raise e

    def get_alter_text(self):
        try:
            text = self.dirver.switch_to.alert.text
        except Exception as e:
            raise e
        return text

    def javascript(self, scr):
        try:
            self.dirver.execute(scr)
        except Exception as e:
            raise e

    def sendKeys(self, loc, value):
        el = self.get_element(*loc)
        try:
            el.clear()
            el.send_keys(value)
        except Exception as e:
            raise e

    def getAttribute(self, loc, name):
        el = self.get_element(*loc)
        if not isinstance(name, str):
            raise NameError
        attr = el.get_attribute(name)
        if not attr:
            print("元素获取失败")
        return attr